package com.yfree.socket

import com.corundumstudio.socketio.AckRequest
import com.corundumstudio.socketio.Configuration
import com.corundumstudio.socketio.SocketIOClient
import com.corundumstudio.socketio.SocketIOServer
import org.slf4j.LoggerFactory

class YSocketManager {
    companion object {
        var socketClients = hashMapOf<String, SocketIOClient>()

        private var socketIOServer: SocketIOServer? = null

        fun init(hostname: String, port: Int, onReceive: (socketIOClient: SocketIOClient, message: String, ackRequest: AckRequest) -> Unit) {
            socketIOServer?.stop()
            val config = Configuration()
            config.hostname = hostname
            config.port = port
            config.socketConfig.isTcpNoDelay = true
            config.socketConfig.soLinger = 0
            config.socketConfig.isTcpKeepAlive = true
            config.maxFramePayloadLength = 1048576 // 设置最大每帧处理数据的长度，防止他人利用大数据来攻击服务器
            config.maxHttpContentLength = 1048576 // 设置http交互最大内容长度
            config.bossThreads = 1 // socket连接数大小（如只监听一个端口boss线程组为1即可）
            config.workerThreads = 100
            config.isAllowCustomRequests = true
            config.upgradeTimeout = 1000000 // 协议升级超时时间（毫秒），默认10秒。HTTP握手升级为ws协议超时时间
            config.pingTimeout = 6000000 // Ping消息超时时间（毫秒），默认60秒，这个时间间隔内没有接收到心跳消息就会发送超时事件
            config.pingInterval = 25000 // Ping消息间隔（毫秒），默认25秒。客户端向服务器发送一条心跳消息间隔
            socketIOServer = SocketIOServer(config)
            socketIOServer!!.addConnectListener {
                socketClients[it.sessionId.toString()] = it
            }
            socketIOServer!!.addDisconnectListener {
                socketClients.remove(it.sessionId.toString())
            }
            socketIOServer!!.addEventListener("client", String::class.java) { socketIOClient: SocketIOClient, message: String, ackRequest: AckRequest ->
                onReceive(socketIOClient, message, ackRequest)
            }
            socketIOServer!!.start()
        }

        fun log(message: String) {
            LoggerFactory.getLogger("YSocketManager").info(message)
        }
    }
}
